package com.ysy.mybatis.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.Data;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 数据库连接池配置
 *
 * @author zxs
 * @since 2019-09-24
 */
@Data
@Configuration(proxyBeanMethods = false)
//@ConditionalOnProperty("spring.datasource.hikari.driver-class-name")
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@ConfigurationProperties("spring.datasource.hikari")
public class HikariDataSourceConfig {
    private String driverClassName;
    private String username;
    private String password;
    private String url;

    @Bean(destroyMethod = "close")
    public HikariDataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setJdbcUrl(url); //数据源
        dataSource.setUsername(username); //用户名
        dataSource.setPassword(password); //密码
        dataSource.addDataSourceProperty("cachePrepStmts", "true"); //是否自定义配置，为true时下面两个参数才生效
        dataSource.addDataSourceProperty("prepStmtCacheSize", "250"); //连接池大小默认25，官方推荐250-500
        dataSource.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); //单条语句最大长度默认256，官方推荐2048
        dataSource.addDataSourceProperty("useServerPrepStmts", "true"); //新版本MySQL支持服务器端准备，开启能够得到显著性能提升
        //config.addDataSourceProperty("useLocalSessionState", "true");
        //config.addDataSourceProperty("useLocalTransactionState", "true");
        dataSource.addDataSourceProperty("rewriteBatchedStatements", "true");
        dataSource.addDataSourceProperty("cacheResultSetMetadata", "true");
        dataSource.addDataSourceProperty("cacheServerConfiguration", "true");
        dataSource.addDataSourceProperty("elideSetAutoCommits", "true");
        dataSource.addDataSourceProperty("maintainTimeStats", "false");
        return dataSource;
    }
}
